package cn.Alibaba.org.service.impl;

import cn.Alibaba.basic.service.impl.BaseServiceImpl;
import cn.Alibaba.basic.util.PageList;
import cn.Alibaba.org.domain.Department;
import cn.Alibaba.org.mapper.DepartmentMapper;
import cn.Alibaba.org.query.DepartmentQuery;
import cn.Alibaba.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Transactional
    @Override
    public void save(Department department) {

        departmentMapper.add(department);


        if (department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else {
            String dirPath = departmentMapper.loadOne(department.getParent_id()).getDirPath();
            department.setDirPath(dirPath+"/"+department.getId());
        }


       update(department);



    }

    @Transactional
    @Override
    public void update(Department department) {


        if (department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else {
            String dirPath = departmentMapper.loadOne(department.getParent_id()).getDirPath();
            department.setDirPath(dirPath+"/"+department.getId());
        }

        departmentMapper.update(department);

    }






    @Override
    public List<Department> deptTree() {


       // 先查询所有
        List<Department> all = departmentMapper.loadAll();
        HashMap<Long, Department> map = new HashMap<>();

        for (Department department : all) {

            map.put(department.getId(),department);
        }

        //前端需要
        ArrayList<Department> deptTree = new ArrayList<>();
        for (Department department : all) {
            if (department.getParent_id()==null){
                deptTree.add(department);

            }else {

                Long parent_id = department.getParent_id();
                Department department1 = map.get(parent_id);
                department1.getChildren().add(department);

            }

        }

        return deptTree;
    }
}
